package com.crm.config;

import java.util.ArrayList;
import java.util.List;


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 登录拦截器
 * 
 * @author SMILE
 */
@Configuration
public class LoginInterceptor extends HandlerInterceptorAdapter implements WebMvcConfigurer {

	// @Override
	// public boolean preHandle(HttpServletRequest request, HttpServletResponse
	// response, Object handler)
	// throws Exception {
	// System.out.println("preHandle。。。。。");
	// //判断请求中是否存在对应的session对象
	// if (request.getSession().getAttribute(USER_KEY) == null) {
	// //session中无对应对象元素，且请求方式为ajax
	// if (AppUtils.isAjax(request)) {
	// response.sendError(401);
	// } else {
	// //跳转到页面首页
	// response.sendRedirect(request.getContextPath() + "/");
	// }
	// return false;//拦截
	// }
	// return true;//放行
	// }
	//
	// /* 登录拦截的地址
	// * 假设请求http://localhost:8080/emp/list/1002。如果没有对应的session对象，则会默认转到首页
	// * webapp/index.jsp
	// * 首页不存在，则会启动全局异常，跳转到error.jsp页面
	// */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		System.out.println("登录地址拦截。。。。。");
		registry.addInterceptor(this)
				// 拦截的地址
				.addPathPatterns("/index")
				// 拦截排除的地址
				.excludePathPatterns("/", "/login", "/error", "/js/**", "/css/**", "/imgs/**");
	}
	@Bean
	public FilterRegistrationBean filterRegistrationBean() {
		FilterRegistrationBean<LoginFilter> registrationBean = new FilterRegistrationBean<LoginFilter>();
		registrationBean.setFilter(new LoginFilter());
		List<String> urlPatterns = new ArrayList<String>();
		urlPatterns.add("/");
		urlPatterns.add("/index");
		urlPatterns.add("/index1");
		urlPatterns.add("/index2");
		urlPatterns.add("/aftersale/**");
		urlPatterns.add("/authority/**");
		urlPatterns.add("/customer/**");
		urlPatterns.add("/sales/**");
		urlPatterns.add("/emp/**");
		urlPatterns.add("/product/**");
		urlPatterns.add("/sales/**");
		urlPatterns.add("/statistics/**");
		registrationBean.setUrlPatterns(urlPatterns);
		return registrationBean;
	}
}
